<script setup>
import { ref, watch, onMounted } from "vue";
import {
  getStuList,
  getStuById,
  addStu,
  updateStu,
  delStu,
  handleVio,
} from "@/api/stu";
import { getAllClazz } from "@/api/clazz";
import { Plus, Edit, Delete, Warning } from "@element-plus/icons-vue";
import { ElMessageBox, ElMessage } from "element-plus";

// 定义搜索表单
const searchForm = ref({
  name: "",
  degree: "",
  clazzId: "",
});

// 定义表格数据
const studentList = ref([]);

// 学历映射关系,1:初中,2:高中,3:大专,4:本科,5:硕士,6:博士
const degreeMap = {
  1: "初中",
  2: "高中",
  3: "大专",
  4: "本科",
  5: "硕士",
  6: "博士",
};

// 学历列表
const degreeList = ref([
  { label: "初中", value: 1 },
  { label: "高中", value: 2 },
  { label: "大专", value: 3 },
  { label: "本科", value: 4 },
  { label: "硕士", value: 5 },
  { label: "博士", value: 6 },
]);

// 班级列表
const clazzList = ref([]);
// 获取班级列表
const getClaList = async () => {
  const res = await getAllClazz();
  if (res.code) {
    clazzList.value = res.data;
  } else {
    ElMessage.error(res.msg);
  }
};

// 分页参数
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: "",
});

// 搜索学员
const handleSearch = async () => {
  const params = {
    name: searchForm.value.name,
    degree: searchForm.value.degree,
    clazzId: searchForm.value.clazzId,
    page: pagination.value.currentPage,
    pageSize: pagination.value.pageSize,
  };
  const res = await getStuList(params);
  if (res.code) {
    studentList.value = res.data.rows;
    pagination.value.total = res.data.total;
  } else {
    ElMessage.error(res.message);
  }
};

// 重置搜索表单
const handleReset = () => {
  searchForm.value = {
    name: "",
    degree: "",
    clazzId: "",
  };
  handleSearch();
};

// 分页相关
const handleSizeChange = (val) => {
  pagination.value.pageSize = val;
  handleSearch();
};
const handleCurrentChange = (val) => {
  pagination.value.currentPage = val;
  handleSearch();
};

// 控制对话框显示
const dialogVisible = ref(false);
const violationDialogVisible = ref(false);
const dialogTitle = ref("新增学员");

// 定义表单引用
const studentFormRef = ref(null);
const violationFormRef = ref(null);

// 定义表单数据
const studentForm = ref({
  no: "",
  name: "",
  gender: "",
  phone: "",
  idCard: "",
  isCollege: "",
  address: "",
  degree: "",
  graduationDate: "",
  clazzId: "",
});

// 表单校验规则
const rules = ref({
  name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  no: [{ required: true, message: "请输入学号", trigger: "blur" }],
  gender: [{ required: true, message: "请选择性别", trigger: "blur" }],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  idCard: [
    { required: true, message: "请输入身份证号", trigger: "blur" },
    {
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: "请输入正确的身份证号",
      trigger: "blur",
    },
  ],
  isCollege: [{ required: true, message: "请选择是否在校", trigger: "blur" }],
});

// 保存学员
const save = async () => {
  await studentFormRef.value.validate();

  let res = null;
  if (studentForm.value.id) {
    res = await updateStu(studentForm.value);
  } else {
    res = await addStu(studentForm.value);
  }

  if (res.code) {
    ElMessage.success("保存成功!");
    dialogVisible.value = false;
    handleSearch();
  } else {
    ElMessage.error(res.msg);
  }
};

// 新增学员
const handleAdd = () => {
  if (studentFormRef.value) {
    studentFormRef.value.resetFields();
  }
  studentForm.value = {
    no: "",
    name: "",
    gender: "",
    phone: "",
    idCard: "",
    isCollege: "",
    address: "",
    degree: "",
    graduationDate: "",
    clazzId: "",
  };
  dialogTitle.value = "新增学员";
  dialogVisible.value = true;
};

// 编辑学员
const handleEdit = async (id) => {
  const res = await getStuById(id);
  if (res.code) {
    studentForm.value = res.data;
    dialogTitle.value = "编辑学员";
    dialogVisible.value = true;
    if (studentFormRef.value) {
      studentFormRef.value.resetFields();
    }
  } else {
    ElMessage.error(res.msg);
  }
};

// 违纪表单
const violationForm = ref({
  id: "", // 学员ID
  violationScore: "",
});

// 违纪扣分
const handleViolation = (student) => {
  violationForm.value = {
    id: student.id, // 设置学员ID
    violationScore: "", // 默认扣1分
  };
  violationDialogVisible.value = true;
};

// 提交违纪登记
const submitViolation = async () => {
  const res = await handleVio(
    violationForm.value.id,
    violationForm.value.violationScore
  );
  if (res.code) {
    ElMessage.success("保存成功!");
    violationDialogVisible.value = false;
    handleSearch(); // 刷新表格数据
  } else {
    ElMessage.error(res.msg);
  }
};

const ids = ref([]); // 选中的id集合

// 获取选中的学员id数组
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id);
};

// 删除学员
const handleDelete = (id) => {
  ElMessageBox.confirm("确定要删除该学员吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const res = await delStu(id);
    if (res.code) {
      ElMessage.success("删除成功!");
      handleSearch();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

// 批量删除
const handleBatchDelete = () => {
  if (ids.value.length === 0) {
    ElMessage.warning("请选择要删除的学员!");
    return;
  }
  ElMessageBox.confirm("确定要批量删除选中的学员吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const res = await delStu(ids.value);
    if (res.code) {
      ElMessage.success("批量删除成功!");
      handleSearch();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

// 初始化
onMounted(() => {
  handleSearch();
  getClaList();
});
</script>

<template>
  <h1>学员管理</h1>

  <!------------ 搜索表单 ------------>
  <el-form :model="searchForm" class="searchForm">
    <el-form-item label="姓名：" class="form-item">
      <el-input
        v-model="searchForm.name"
        placeholder="请输入姓名"
        class="search-item"
        clearable
      />
    </el-form-item>
    <el-form-item label="最高学历：" class="form-item">
      <el-select
        v-model="searchForm.degree"
        placeholder="请选择学历"
        class="search-item"
        clearable
      >
        <el-option
          v-for="item in degreeList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="所属班级：" class="form-item">
      <el-select
        v-model="searchForm.clazzId"
        placeholder="请选择班级"
        class="search-item"
        clearable
      >
        <el-option
          v-for="item in clazzList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
    </el-form-item>
    <el-form-item class="form-item-btn">
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="handleReset">清空</el-button>
    </el-form-item>
  </el-form>

  <!------------ 操作按钮 ------------>
  <div class="action-buttons">
    <el-button type="primary" :icon="Plus" @click="handleAdd">
      新增学员</el-button
    >
    <el-button type="danger" :icon="Delete" @click="handleBatchDelete"
      >批量删除</el-button
    >
  </div>

  <!------------ 表格和分页 ------------>
  <el-table
    :data="studentList"
    border
    style="width: 100%; margin-top: 3px"
    @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" width="55" align="center" />
    <el-table-column prop="name" label="姓名" width="120" align="center" />
    <el-table-column prop="no" label="学号" width="125" align="center" />
    <el-table-column prop="clazzName" label="班级" width="175" align="center" />
    <el-table-column label="性别" width="80" align="center">
      <template #default="{ row }">
        {{ row.gender === 1 ? "男" : "女" }}
      </template>
    </el-table-column>
    <el-table-column prop="phone" label="手机号" width="135" align="center" />
    <el-table-column label="学历" width="100" align="center">
      <template #default="{ row }">
        {{ degreeMap[row.degree] }}
      </template>
    </el-table-column>
    <el-table-column
      prop="violationCount"
      label="违纪次数"
      width="90"
      align="center"
    />
    <el-table-column
      prop="violationScore"
      label="违纪扣分"
      width="90"
      align="center"
    />
    <el-table-column
      prop="updateTime"
      label="最后操作时间"
      width="180"
      align="center"
    />
    <el-table-column label="操作" align="center">
      <template #default="{ row }">
        <el-button
          type="primary"
          size="small"
          class="action-button"
          :icon="Edit"
          @click="handleEdit(row.id)"
          >编辑</el-button
        >
        <el-button
          type="warning"
          size="small"
          class="action-button"
          :icon="Warning"
          @click="handleViolation(row)"
          >违纪</el-button
        >
        <el-button
          type="danger"
          size="small"
          class="action-button"
          :icon="Delete"
          @click="handleDelete(row.id)"
          >删除</el-button
        >
      </template>
    </el-table-column>
  </el-table>

  <el-pagination
    style="margin-top: 20px"
    v-model:current-page="pagination.currentPage"
    v-model:page-size="pagination.pageSize"
    :total="pagination.total"
    layout="total, sizes, prev, pager, next, jumper"
    :page-sizes="[5, 10, 20, 30]"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />

  <!------------ 新增/修改学员对话框 ------------>
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%">
    <el-form
      ref="studentFormRef"
      :model="studentForm"
      label-width="125px"
      :rules="rules"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input
              v-model="studentForm.name"
              placeholder="请输入姓名"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="学号" prop="no">
            <el-input
              v-model="studentForm.no"
              placeholder="请输入学号"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select
              v-model="studentForm.gender"
              placeholder="请选择性别"
              style="width: 100%"
            >
              <el-option label="男" :value="1"></el-option>
              <el-option label="女" :value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input
              v-model="studentForm.phone"
              placeholder="请输入手机号"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="身份证号" prop="idCard">
            <el-input
              v-model="studentForm.idCard"
              placeholder="请输入身份证号"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否院校学员" prop="isCollege">
            <el-select
              v-model="studentForm.isCollege"
              placeholder="请选择"
              style="width: 200%"
            >
              <el-option label="是" :value="1"></el-option>
              <el-option label="否" :value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系地址" prop="address">
            <el-input
              v-model="studentForm.address"
              placeholder="请输入联系地址"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最高学历" prop="degree">
            <el-select
              v-model="studentForm.degree"
              placeholder="请选择"
              style="width: 200%"
            >
              <el-option
                v-for="(item, index) in degreeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="毕业时间" prop="graduationDate">
            <el-date-picker
              v-model="studentForm.graduationDate"
              type="date"
              placeholder="请选择毕业时间"
              style="width: 100%"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属班级" prop="clazzId">
            <el-select
              v-model="studentForm.clazzId"
              placeholder="请选择"
              style="width: 200%"
            >
              <el-option
                v-for="(item, index) in clazzList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="save">保存</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </span>
    </template>
  </el-dialog>

  <!------------ 违纪登记对话框 ------------>
  <el-dialog v-model="violationDialogVisible" title="学员违纪处理" width="18%">
    <el-form ref="violationFormRef" :model="violationForm" width="50%">
      <el-form-item label="违纪扣分" label-width="80px">
        <el-input v-model="violationForm.violationScore"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="submitViolation">确定</el-button>
        <el-button @click="violationDialogVisible = false">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
h1 {
  color: blueviolet;
  font-family: "SimSun";
  font-size: 28px;
  font-weight: bold;
}

.searchForm {
  display: flex;
  align-items: center;
  margin-top: 12px;
  margin-bottom: 10px;
}

.form-item {
  display: flex;
  align-items: center;
  margin-right: 45px;
}

:deep(.el-form-item__label) {
  font-size: 15px;
  color: #606266;
}

.search-item {
  width: 280px;
  font-size: 16px;
}

.el-input__inner,
.el-select__input,
.el-date-editor .el-range-input {
  height: 40px;
  line-height: 40px;
  padding: 0 10px;
}

.el-button {
  height: 35px;
  font-size: 16px;
  padding: 0 20px;
}

.form-item-btn {
  height: 20px;
  font-size: 14px;
  padding: 0 8px;
  margin-right: 5px;
  align-items: center;
  margin-left: 10px;
}

.action-button {
  padding: 5px 10px; /* 调整内边距 */
  font-size: 12px; /* 调整字体大小 */
  height: 24px; /* 调整按钮高度 */
}

.action-buttons {
  margin-top: 12px;
  margin-bottom: 18px;
  display: flex;
  gap: 10px;
}

.el-button {
  height: 40px;
  font-size: 16px;
  padding: 0 15px;
  border-radius: 4px;
  transition: background-color 0.3s, border-color 0.3s;
}

.action-button {
  height: 30px;
  font-size: 14px;
  padding: 0 8px;
  margin-right: 5px;
  width: 75px;
}

.el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
}

.el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.el-button--danger {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

.el-button--danger:hover {
  background-color: #ff7875;
  border-color: #ff7875;
}

.el-button--warning {
  background-color: #e6a23c;
  border-color: #e6a23c;
}

.el-button--warning:hover {
  background-color: #ebb563;
  border-color: #ebb563;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  text-align: center;
  border: 1px dashed var(--el-border-color);
}

/* 修改新增/编辑学员对话框宽度 */
:deep(.el-dialog) {
  width: 60% !important;
}

/* 统一表单项内的控件宽度，并增加内边距对齐 */
:deep(.el-dialog .el-form-item__content) {
  width: 100%;
}

/* 表单项中输入组件统一宽度（如 input、select、date-picker） */
:deep(.el-dialog .el-input, .el-dialog .el-select, .el-dialog .el-date-editor) {
  width: 100%;
}

.dialog-footer {
  /*底部按钮居中*/
  display: flex;
  justify-content: center;
  margin: auto;
  /*底部按钮间距*/
  gap: 10px;
  .el-button {
    width: 120px;
  }
}
</style>
